package estring

import (
	"reflect"

	"gitee.com/haodreams/golib/snaker"
)

//GetNameStruct 获取类名
func GetNameStruct(class interface{}, isSnake ...bool) (title string) {
	v := reflect.ValueOf(class)
	v = reflect.Indirect(v)
	t := v.Type()
	title = t.Name()
	if len(isSnake) > 0 && isSnake[0] {
		title = snaker.CamelToSnake(title)
	}
	return
}

//GetTitlesFromStruct 获取类中的成员变量和变量对应的值
func GetTitlesFromStruct(class interface{}) (titles []string) {
	v := reflect.ValueOf(class)
	if v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	} else if v.Kind() != reflect.Struct {
		return
	}

	t := v.Type()

	for i := 0; i < v.NumField(); i++ {
		fieldType := t.Field(i)
		name := snaker.CamelToSnake(fieldType.Name)
		titles = append(titles, name)
	}
	return
}

//GetStructValues 获取字段对应的值
func GetStructValues(class interface{}) (values []interface{}) {
	v := reflect.ValueOf(class)
	if v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	} else if v.Kind() != reflect.Struct {
		return
	}

	values = make([]interface{}, v.NumField())
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)
		typField := field.Type()
		if typField.Kind() == reflect.Ptr {
			if field.IsNil() {
				values[i] = nil
			} else {
				field = reflect.Indirect(field)
				//field = field.Elem() //2种方法等效
				values[i] = field.Interface()
			}
		} else {
			values[i] = field.Interface()
		}
	}
	return
}
